﻿using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;

// The Templated Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234235

namespace StyleMVVM.Controls.Layouts
{
	public sealed class VariableGridView : GridView
	{
		public string ItemRowSpanPropertyPath
		{
			get { return (string)GetValue(InternalItemRowSpanPropertyPathProperty); }
			set { SetValue(InternalItemRowSpanPropertyPathProperty, value); }
		}

		public static DependencyProperty ItemRowSpanPropertyPathProperty
		{
			get { return InternalItemRowSpanPropertyPathProperty; }
		}

		// Using a DependencyProperty as the backing store for ItemRowSpanPropertyPath.  This enables animation, styling, binding, etc...
		internal static readonly DependencyProperty InternalItemRowSpanPropertyPathProperty =
			DependencyProperty.Register("ItemRowSpanPropertyPath",
			                            typeof(string),
			                            typeof(VariableGridView),
			                            new PropertyMetadata(string.Empty));

		public string ItemColSpanPropertyPath
		{
			get { return (string)GetValue(InternalItemColSpanPropertyPathProperty); }
			set { SetValue(InternalItemColSpanPropertyPathProperty, value); }
		}

		public static DependencyProperty ItemColSpanPropertyPathProperty
		{
			get { return InternalItemColSpanPropertyPathProperty; }
		}

		// Using a DependencyProperty as the backing store for ItemColSpanPropertyPath.  This enables animation, styling, binding, etc...
		internal static readonly DependencyProperty InternalItemColSpanPropertyPathProperty =
			DependencyProperty.Register("ItemColSpanPropertyPath",
			                            typeof(string),
			                            typeof(VariableGridView),
			                            new PropertyMetadata(string.Empty));

		protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
		{
			base.PrepareContainerForItemOverride(element, item);

			UIElement uiElement = element as UIElement;

			Binding colBinding = new Binding();
			colBinding.Source = item;
			colBinding.Path = new PropertyPath(this.ItemColSpanPropertyPath);
			BindingOperations.SetBinding(uiElement, VariableSizedWrapGrid.ColumnSpanProperty, colBinding);

			Binding rowBinding = new Binding();
			rowBinding.Source = item;
			rowBinding.Path = new PropertyPath(this.ItemRowSpanPropertyPath);
			BindingOperations.SetBinding(uiElement, VariableSizedWrapGrid.RowSpanProperty, rowBinding);
		}
	}
}